package utils

import (
	"bufio"
	"encoding/json"
	"io"
	"os"
	"strings"
)

type Monster struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Skill string `json:"skill"`
}

func (m *Monster) Store(path string) error {
	data, err := json.Marshal(m)
	if err != nil {
		return err
	}
	if !strings.HasSuffix(path, "/") {
		path += "/"
	}
	file, err := os.OpenFile(path+m.Name, os.O_WRONLY|os.O_CREATE, 0777)
	if err != nil {
		return err
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	_, err = writer.WriteString(string(data))
	if err != nil {
		return err
	}
	writer.Flush()
	return nil
}

func (m *Monster) ReStore(filePath string) error {
	file, err := os.OpenFile(filePath, os.O_RDONLY, 0777)
	if err != nil {
		return err
	}
	defer file.Close()
	reader := bufio.NewReader(file)
	var jsonStr string
	for {
		str, err := reader.ReadString('\n')
		jsonStr += str
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
	}
	err = json.Unmarshal([]byte(jsonStr), m)
	if err != nil {
		return err
	}
	return nil
}
